package mrusanov.images

import java.awt.{Point, AlphaComposite, Graphics2D}
import java.awt.image.BufferedImage

object Image {
  def apply(path:String, xOffset:Int, yOffset:Int, alpha:Float):Image =
    new LazyImage(path, xOffset, yOffset, alpha)

  def apply(path:String, xOffset:Int, yOffset:Int):Image = apply(path, xOffset, yOffset, 1f)

  def apply(path:String):Image = apply(path, 0, 0)

  def apply(bufferedImage:BufferedImage, xOffset:Int, yOffset:Int, alpha:Float):Image = new EagerImage(bufferedImage, xOffset, yOffset, alpha)

  def apply(bufferedImage:BufferedImage, xOffset:Int, yOffset:Int):Image = apply(bufferedImage, xOffset, yOffset, 1f)

  def apply(bufferedImage:BufferedImage):Image = apply(bufferedImage, 0, 0)
}

abstract class Image private[images] (val xOffset:Int, val yOffset:Int, val alpha:Float) {

  val defaultAlpha = 1f
  def imagePath:Option[String]

  def bufferedImage:BufferedImage

  def render(g:Graphics2D, p:Point) { render(g, p.x, p.y) }

  def render(g:Graphics2D, x:Int, y:Int) {
    if (alpha != defaultAlpha) {
      g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha))
      g.drawImage(bufferedImage, xOffset + x, yOffset + y, null)
      g.setComposite(AlphaComposite.SrcOver)
    } else {
      g.drawImage(bufferedImage, xOffset + x, yOffset + y, null)
    }
  }

  def width = bufferedImage.getWidth

  def height = bufferedImage.getHeight
}
